/*
 * Clase que instancia la interfaz grafica para el manejo del chat
 * por parte del cliente.
 * CLASE SUSTRAIDA DE UNA PAGINA WEB
 */
package servclien;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClientGUI extends JFrame implements ActionListener {

    private static final long _serialVersionUID = 1L;
    private JLabel _label;
    private JTextField _tf;
    private JTextField _tfServer, _tfPort;
    private JButton _login, _logout, _WhoIsIn;
    private JTextArea _ta;
    private boolean _connected;
    private Client _client;
    private int _defaultPort;
    private String _defaultHost;
    private String _Username;

    /**
     * Constructor, conexion que recibe un numero de socket
     *
     * @param host Nombre Cliente a unirse al chat
     * @param port Puerto de la conexion
     */
    ClientGUI(String pHost, int pPort) {
        super("Chat Client");
        _defaultPort = pPort;
        _defaultHost = pHost;

        JPanel northPanel = new JPanel(new GridLayout(3, 1));
        JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3));
        _tfServer = new JTextField(pHost);
        _tfPort = new JTextField("" + pPort);
        _tfPort.setHorizontalAlignment(SwingConstants.RIGHT);

        serverAndPort.add(new JLabel("Server Address:  "));
        serverAndPort.add(_tfServer);
        serverAndPort.add(new JLabel("Port Number:  "));
        serverAndPort.add(_tfPort);
        serverAndPort.add(new JLabel(""));
        northPanel.add(serverAndPort);

        _label = new JLabel("Enter your username below", SwingConstants.CENTER);
        northPanel.add(_label);
        _tf = new JTextField("Username");
        _tf.setBackground(Color.WHITE);
        northPanel.add(_tf);
        add(northPanel, BorderLayout.NORTH);

        _ta = new JTextArea("Welcome to the Chat room\n", 80, 80);
        JPanel centerPanel = new JPanel(new GridLayout(1, 1));
        centerPanel.add(new JScrollPane(_ta));
        _ta.setEditable(false);
        add(centerPanel, BorderLayout.CENTER);

        _login = new JButton("Login");
        _login.addActionListener(this);
        _logout = new JButton("Logout");
        _logout.addActionListener(this);
        _logout.setEnabled(false);
        _WhoIsIn = new JButton("Who is in");
        _WhoIsIn.addActionListener(this);
        _WhoIsIn.setEnabled(false);

        JPanel southPanel = new JPanel();
        southPanel.add(_login);
        southPanel.add(_logout);
        southPanel.add(_WhoIsIn);
        add(southPanel, BorderLayout.SOUTH);

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(400, 300);
		setVisible(true);
		_tf.requestFocus();

    }

    /**
     * Concatena los mensajes al area de texto de la interfaz grafica.
     *
     * @param pStr Mensaje a mostrar y concatenar
     */
    void append(String pStr) {
        _ta.append(pStr);
        _ta.setCaretPosition(_ta.getText().length() - 1);
    }

    /**
     * Llamado por la GUI si la conexion falla se reestablecen los botones
     */
    void connectionFailed() {
        _login.setEnabled(true);
        _logout.setEnabled(false);
        _WhoIsIn.setEnabled(false);
        _label.setText("Enter your username below");
        _tf.setText(_Username);
        _tfPort.setText("" + _tfPort.getText());
        _tfServer.setText(_tfServer.getText());
        _tfServer.setEditable(true);
        _tfPort.setEditable(true);
        _tf.removeActionListener(this);
        _connected = false;
    }

    @Override
    public void actionPerformed(ActionEvent pE) {
        Object o = pE.getSource();
        if (o == _logout) {
            _client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
            return;
        }

        if (o == _WhoIsIn) {
            _client.sendMessage(new ChatMessage(ChatMessage._whoIsIn, ""));
            return;
        }

        if (_connected) {
            _client.sendMessage(new ChatMessage(ChatMessage._messageNumber, _tf.getText().trim()));
            _tf.setText("");
            return;
        }

        if (o == _login) {
            _Username = _tf.getText().trim();
            
            if (_Username.length() == 0) {
                return;
            }
            
            String server = _tfServer.getText().trim();
            if (server.length() == 0) {
                return;
            }
            
            String portNumber = _tfPort.getText().trim();
            if (portNumber.length() == 0) {
                return;
            }
            
            int port = 0;
            try {
                port = Integer.parseInt(portNumber);
            } catch (Exception en) {
                return;   
            }

            
            _client = new Client(server, port, _Username, this);
           
            if (!_client.start()) {
                return;
            }
            _tf.setText("");
            _label.setText("Enter your message below");
            _connected = true;

            _login.setEnabled(false);
            
            _logout.setEnabled(true);
            _WhoIsIn.setEnabled(true);
            
            _tfServer.setEditable(false);
            _tfPort.setEditable(false);
            
            _tf.addActionListener(this);
        }
    }

    public static void main(String[] pArgs) {
        new ClientGUI("localhost", 1500);
    }
}
